package me.teacms.controller.common;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import me.teacms.common.result.JsonResult;
import me.teacms.common.utils.DateUtil;
import me.teacms.dao.MultimediaMapper;
import me.teacms.entity.Multimedia;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;

import static com.sun.tools.doclint.Entity.Mu;
import static com.sun.tools.doclint.Entity.nu;

/**
 * Author: XiaoBingBy
 * Email: XiaoBingBy@qq.com
 * Date: 2017/2/22
 * Time: 1:32
 * Describe: 写文章图片上传
 */
@Controller
public class UploadImgController {

    @Autowired
    private MultimediaMapper multimediaMapper;

	@RequestMapping("/admin/upload")
	@ResponseBody
    public String upload(HttpServletRequest request, MultipartFile myFileName) throws Exception {
		
		//获取磁盘路径
		String path = request.getSession().getServletContext().getRealPath("uploads");
        
		//获取上传文件名
		String uploadFileName = myFileName.getOriginalFilename();
		
		int year = DateUtil.getYear();	//年
		
		int month = DateUtil.getMonth();	//月
		
		
		//创建文件
        File targetFile = new File(path+"/"+year+"/"+month, uploadFileName);
        if(!targetFile.exists()){  
            targetFile.mkdirs();  //创建文件
        }
        
        myFileName.transferTo(targetFile);	//写入文件
		
        //TODO 后期优化，设置成域名
        
        //写入数据库
       /* Multimedia multimedia = new Multimedia();
        Date createDate = new Date();
        multimedia.setFileName(uploadFileName);
        multimedia.setFileUrl(WebCacheUtil.getWebCacheUtil().getWebConfig().getDomainName()+"uploads"+"/"+year+"/"+month+"/"+uploadFileName);
		multimedia.setCreateDate(createDate);
        int addImgNameUrl = uploadImgService.addImgNameUrl(multimedia);
        
        if (addImgNameUrl >= 1) {	//上传成功
        	return multimedia.getFileUrl();
		}*/
		
       /* return WebCacheUtil.getWebCacheUtil().getWebConfig().getDomainName()+"uploads"+"/"+year+"/"+month+"/"+uploadFileName;*/
        Multimedia multimedia = new Multimedia();
        multimedia.setFileName(uploadFileName);
        multimedia.setFileType(0);
        multimedia.setFileUrl("/uploads"+"/"+year+"/"+month+"/"+uploadFileName);
        multimedia.setCreateDate(new Date());
        multimediaMapper.insert(multimedia);
       return "/uploads"+"/"+year+"/"+month+"/"+uploadFileName;
    }

}